<template>
  <form-wrap :rules="rules" :schema="formSchema" @register="formRegister" />
</template>
<script setup lang="ts">
  import { useForm } from '@/hooks/form';
  import { useValidator } from '@/hooks/validator';

  const { required, lengthRange, checkPassword } = useValidator();

  const formSchema = ref<FormSchema[]>([
    {
      field: 'password',
      label: '密码',
      type: 'Password',
      componentProps: {
        showPassword: true,
        maxlength: 18,
        minlength: 6,
      },
      info: '请输入6-18位的新密码，支持大小写字母及数字',
    },
    {
      field: 'repassword',
      label: '确认密码',
      type: 'Password',
      componentProps: {
        showPassword: true,
        maxlength: 18,
        minlength: 6,
      },
    },
  ]);

  const rules = reactive({
    password: [required(), checkPassword()],
    repassword: [
      required(),
      lengthRange({ min: 6, max: 18 }),
      {
        validator: async (val: string, callback: (error?: string) => void) => {
          const formData = await getFormData();
          const { password } = formData;
          if (val !== password) {
            callback('密码不一致');
          } else {
            callback();
          }
        },
      },
    ],
  });

  const { formRegister, formMethods } = useForm();
  const { submitForm, getFormData } = formMethods;

  const submit = async () => {
    return await submitForm();
  };

  defineExpose({
    submit,
  });
</script>
